﻿(function () {
    'use strict';
    var serviceId = 'loginServece';
    angular.module('app').factory(serviceId, ['common', loginServece]);

    function loginServece(common, signalR) {

        var requester = common.httpRequestSvc;
        var redirector = common.pageLocatorSvc;

        var service = {
            loginUser: loginUser
        };

        return service;

        function onTokenGotError(err) {
            console.log(JSON.stringify(err));
            alert("Error in logging user [from login-controller]");
        };

        function createUserDataString(userName, password) {
            var userDataString = "grant_type=password&username=" + userName + "&password=" + password;
            return userDataString;
        }

        function loginUser(userName, password) {

            var userDataString = createUserDataString(userName, password);

            console.log(JSON.stringify(userDataString, null, 4));

            requester.postJson("http://localhost:15930/Token", userDataString)
                .then(function (data) {
                    console.log(data);
                    return data;
                }, function (err) {
                    onTokenGotError(err);
                })
                .then(function (data) {
                var a = 5;
                    var user = {
                        userName: data.userName,
                        authCode: null
                    };

                    requester.postJson("http://localhost:15930/api/Users/get-all", user, data.access_token)
                             .then(function (resevedData) {
                                 console.log(resevedData);
                        console.log(JSON.stringify(resevedData, null, 4));
                                 // redirector.goTo('/chat');
                             }, function (err) {
                                 console.log(JSON.stringify(err, null, 4));
                             });
                });
        }
    }
})();







